package sun.cn.common.utils;



import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HTTP 工具类
 * @author sunlingao@zbj.com
 * @title
 * @date 2018年4月26日
 * @version
 */
public final class HttpClientUtils{

    private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
    private static final int TIMEOUT = 1000;
    private static final String DEFAULT_CHARSET = "utf-8";
    private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8";

    private HttpClientUtils(){}

    public static String doGet(String url,int timeout,String contentType){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout)
                    .build());
            httpGet.setHeader("Content-Type",contentType);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity httpEntity = null;
            try {
                httpEntity = response.getEntity();
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    return EntityUtils.toString(httpEntity,DEFAULT_CHARSET);
                }
            } finally {
                EntityUtils.consume(httpEntity);
                response.close();
            }
        } catch (Exception e) {
            LOG.error("doGet url is {} error is {}",url,e);
        } finally {
            org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
        }
        return null;
    }

    public static String doGet(String url){
        return doGet(url, TIMEOUT,DEFAULT_CONTENT_TYPE);
    }
    public static String doGet(String url,int timeout){return doGet(url,timeout,DEFAULT_CONTENT_TYPE);}

    private static String doPost(String url, Map<String,String> params,String body, int timeout,String charset,
                                 String contentType){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try{
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(RequestConfig.custom().setConnectTimeout(TIMEOUT)
            .setSocketTimeout(timeout).build());
            httpPost.setHeader("Content-Type",contentType);
            List<NameValuePair> nvps = null;
            if(params != null){
                nvps = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            if(!CollectionUtils.isEmpty(nvps)) {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
            }
            if(StringUtils.isNotEmpty(body)){
                httpPost.setEntity(new StringEntity(body));
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);
            HttpEntity httpEntity = null;
            try{
                httpEntity = response.getEntity();
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    return EntityUtils.toString(httpEntity,charset);
                }
            }catch(Exception e){
                LOG.error("doPost url is {} error is {}",url,e);
            }finally{
                EntityUtils.consume(httpEntity);
                response.close();
            }
        }catch(Exception e){
            LOG.error("doPost url is {} error is {}",url,e);
        }finally{
            org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
        }
        return null;
    }

    public static String doPost(String url,Map<String,String> params){
        return doPost(url,params,null,TIMEOUT,DEFAULT_CHARSET,DEFAULT_CONTENT_TYPE);
    }

    public static String doPost(String url,String body){
        return doPost(url,null,body,TIMEOUT,DEFAULT_CHARSET,DEFAULT_CONTENT_TYPE);
    }

    public static String doPost(String url, Map<String,String> params, int timeout,String charset){
        return doPost(url,params,null,timeout,charset,DEFAULT_CONTENT_TYPE);
    }

    public static String doPost(String url, String body, int timeout,String charset){
        return doPost(url,null,body,timeout,charset,DEFAULT_CONTENT_TYPE);
    }

    public static String doPost(String url,String body,int timeout,String charset,String contentType){
        return doPost(url,null,body,timeout,charset,contentType);
    }

}
